package com.sun;

import java.awt.*;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 */
public class Test2AddTwoNumbers {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(4);
        ListNode l3 = new ListNode(3);
        l1.next = l2;
        l2.next = l3;

        ListNode m1 = new ListNode(5);
        ListNode m2 = new ListNode(6);
        ListNode m3 = new ListNode(4);
        m1.next = m2;
        m2.next = m3;

        ListNode listNode = addTwoNumbers2(l1, m1);
        printList(listNode);

    }

    /**
     * 自己写的。。
     */
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2){
        ListNode result = new ListNode();
        ListNode returnResult = result;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0){
            int num = 0;
            if (l1 != null){
                num += l1.val;
                l1 = l1.next;
            }
            if (l2 != null){
                num += l2.val;
                l2 = l2.next;
            }
            num += carry;
            carry = num / 10;
            result.next = new ListNode(num % 10);
            result = result.next;
        }
        return returnResult.next;
    }

    /**
     * 官方
     */
    public static ListNode addTwoNumbers2(ListNode l1, ListNode l2){
        ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null){
            int n1 = l1 == null ? 0 : l1.val;
            int n2 = l2 == null ? 0 : l2.val;
            int sum = n1 + n2 + carry;
            if(head == null){
                head = tail = new ListNode(sum % 10);
            }else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum / 10;
            if(l1 != null){
                l1 = l1.next;
            }
            if (l2 != null){
                l2 = l2.next;
            }
        }
        if (carry > 0){
            tail.next = new ListNode(carry);
        }
        return head;
    }

    public static void printList(ListNode listNode){
        while (listNode != null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}

class ListNode{
    int val;
    ListNode next;
    ListNode(){}

    //构造函数
   public ListNode(int val){
        this.val = val;
    }
    ListNode(int val,ListNode next){
        this.val = val;
        this.next = next;
    }
}